package com.qianfeng.libra.cowshop.app.activities;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.PlatformDb;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.framework.utils.UIHandler;
import cn.sharesdk.sina.weibo.SinaWeibo;
import com.qianfeng.libra.cowshop.app.R;
import com.qianfeng.libra.cowshop.app.configuration.Constants;
import com.qianfeng.libra.cowshop.app.tasks.*;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;


public class LoginActivity extends Activity implements TaskProcessor, PlatformActionListener, Handler.Callback, MyProcessor {
    private  String userId;
    private  String token;
    private EditText tel;
    private EditText pass;
    private String userName;
    private ProgressDialog progressDialog;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tel = (EditText)findViewById(R.id.tel);
        pass = (EditText)findViewById(R.id.pass);
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("正在登陆。。。");

    }
    public  void loginOnClick(View view)
    {

        userId=tel.getText().toString().trim();
        token=pass.getText().toString().trim();
        String url="http://s.it168.com/AppService/QHMProduct.asmx/Login?telnum="+userId+"&password="+token;
        DownloadDataTask dataTask=new DownloadDataTask(this);
        dataTask.execute(url);

    }
    public void btnShareOnClick(View v) {
        progressDialog.show();
        ShareSDK.initSDK(this);

        authorize(new SinaWeibo(this));
    }


    /**
     * @param plat 希望用那个平台登录，这个地方就传递那个平台的对象
     */
    private void authorize(Platform plat) {
        if (plat == null) {
            // 如果没有指定平台，那么现在强制选择新浪微博
            plat = new SinaWeibo(this);
        }

        //判断指定平台是否已经完成授权
        // 没有授权的时候，进行授权操作 最终会执行 showUser() 这个方法
        // 作用就是授权并且获取用户信息
        if(plat.isValid()) {
            String userId = plat.getDb().getUserId();
            userName = plat.getDb().getUserName();

            if (userId != null) {
                // 用于发送注册/登陆成功的消息
                UIHandler.sendEmptyMessage(1, this);
                // login(plat.getName(), userId, null);

                Log.d("Login", plat.getName());
                Log.d("Login", userId);

                return;
            }
        }
        // 用于检测用户在登录时操作的状态。
        // 当用户授权成功，会进行回调，回调内部会传递一些用户的信息
        plat.setPlatformActionListener(this);
        // true不使用SSO授权，false使用SSO授权
        plat.SSOSetting(true);
        //获取用户资料
        plat.showUser(null);
    }



    @Override
    public void processResult(JSONObject result) {
        String  userid="";
        String  tokens="";
        try {

            JSONObject jsonObject=result.getJSONObject("info");
            userid=jsonObject.getString("userid");
            tokens=jsonObject.getString("token");

        } catch (JSONException e) {
            e.printStackTrace();
        }
        String url="http://s.it168.com/AppService/QHMProduct.asmx/GetCartList?userid="+userid+"&token="+tokens;
        LoginUpTask dataTask=new LoginUpTask(this);
        dataTask.execute(url);
    }

    @Override
    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
        // 获取哪一个平台的登录授权信息
        PlatformDb db = platform.getDb();
        userId = db.getUserId();
        token=db.getToken();
        userName=db.getUserName();
        Log.d("SSSSSSSSSS","--------->"+userId);
        Log.d("SSSSSSSSSS","--------->"+userName);
        String url = "http://s.it168.com/AppService/QHMProduct.asmx/LoginNew";
        String from="2";
        String[] arr = {url,userId,from};
        SignupTask task = new SignupTask(this);
        task.execute(arr);
    }

    @Override
    public void onError(Platform platform, int i, Throwable throwable) {

    }

    @Override
    public void onCancel(Platform platform, int i) {

    }

    @Override
    public boolean handleMessage(Message msg) {
        return false;
    }

    @Override
    public void myProcessResult(JSONObject result) {
        if (result!=null) {
            try {
                JSONObject info = result.getJSONObject("info");
                int id = info.getInt("state");
                if (id == 1) {
                    SharedPreferences sp = getSharedPreferences("sp", MODE_PRIVATE);
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putString(Constants.USER_ID, userId);
                    editor.putString(Constants.TOKEN, token);
                    editor.putString(Constants.USER_NAME,userName);
                    editor.putBoolean(Constants.IS_LOGIN, true);
                    editor.commit();
                    progressDialog.show();
                    Toast.makeText(this, "登陆成功", Toast.LENGTH_SHORT).show();
                    finish();
                    Intent intent=new Intent(this,PersonActivity.class);
                    startActivity(intent);

                } else {
                    Toast.makeText(this, "登陆失败", Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
        else
        {
            Toast.makeText(this, "登陆失败", Toast.LENGTH_SHORT).show();
        }
    }
}
